package com.moter.demo01.juc.component;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 加法计数器 比如游乐设施,满20人就去进去,不满则继续等待
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(15,()->{
            System.out.println("集齐七颗龙珠,召唤神龙");
        });
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"集齐了第"+"颗龙珠");
                try {
                    cyclicBarrier.await(4,TimeUnit.SECONDS);//所有线程到底这一步等待,直到足够parties数量的线程到底此处,继续向下执行
                    //如果时间到了,还没有放行的话,会抛出TimeoutException(超时)和BrokenBarrierException(冲破栅栏)
                    System.out.println(Thread.currentThread().getName()+"吃香的喝辣的");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
